#include <kutils.h>
#include <string.h>
#include "fdc.h"
#include "display.h"
#include "memory.h"
#include "syscall.h"
#include "vfs.h"

s32int fdc_open_fs(fs_node_t *node);
s32int fdc_close_fs(fs_node_t *node);
s32int fdc_read_fs(fs_node_t *node, u32int offset, u32int size, u8int *buffer);
s32int fdc_create_dev_file(s8int *name);

extern fdc_drive_t *floppy_drives[2];
extern s8int fd_exists[2];
extern fs_node_t *fs_root;

s32int fdc_open_fs(fs_node_t *node)
{
	if(!node)
		return 0;
	//a dummy open function
	return 1;
}

s32int fdc_close_fs(fs_node_t *node)
{
	if(!node)
		return 0;

	//a dummy close function
	return 1;
}

s32int fdc_read_fs(fs_node_t *node, u32int offset, u32int size, u8int *buffer)
{
	if(strcmp((s8int*)node->name,"fda") == 0)
	{
		return fdc_read(floppy_drives[0], buffer, offset, 0, size);
	}
	return 0;
}

//creates a file in the /dev directory through which a device can be read/written
s32int fdc_create_dev_file(s8int *name)
{
	fs_node_t *dev_node = fs_root->first_child;	//the dev directory is gaurenteed to be 
																//the first child of the root
	if(!dev_node)
		return 0;	

	fs_node_t *new_node = (fs_node_t*)kmalloc(sizeof(fs_node_t));
	strcpy((s8int*)new_node->name,name);
	new_node->length = 512; //the standard block size
	new_node->inode = get_valid_inode();
	new_node->flags = FS_FILE;
	new_node->read = &fdc_read_fs;
   new_node->write = 0;
   new_node->open = &fdc_open_fs;
   new_node->close = &fdc_close_fs;
   new_node->ptr = 0;
	new_node->dvr_num = 0;
	new_node->dvr_ptr = 0;
	new_node->parent = dev_node;//it's parent is the /dev node
	new_node->next_sibling = 0;
	new_node->first_child = 0;

	if(dev_node->first_child == 0)//the dev node has no children at this time
	{
		dev_node->first_child = new_node;
	}
	else//the dev node alredy has atleast one child, let's add this new one to the end of the linked list
	{
		fs_node_t *tmp_node = dev_node->first_child;
		while(tmp_node)
		{
			if(tmp_node->next_sibling)
			{
				tmp_node = tmp_node->next_sibling;
			}
			else
			{
				tmp_node->next_sibling = new_node;
				break;
			}
		}
	}

	return 1;
}

void init_fdc_interface(void)
{
	// this function will add all of the detected partitions to 
	// the /dev directory and expose their read/write functions
	// to the proper wrapper functions in this file
	if(fd_exists[0])
	{
		fdc_create_dev_file("fda");
	}
}
